package com.transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Transaction1 {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        String url = "jdbc:mysql://localhost:3306/manger";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, "root", "");
            conn.setAutoCommit(false);
            PreparedStatement stat = conn.prepareStatement("update account set balance = balance - ? where id = ?");
            stat.setDouble(1,8000);
            stat.setInt(2,1);
            int i = stat.executeUpdate();
            if (i > 0){
                System.out.println("转出成功");
            }else {
                System.out.println("转出失败");
            }

            stat.setDouble(1,-8000);
            stat.setInt(2,2);
            int i1 = stat.executeUpdate();
            if (i1 > 0){
                System.out.println("转入成功");
            }else {
                System.out.println("转入失败");
            }
            conn.commit();
            System.out.println("提交事务成功");
        } catch (SQLException e) {
           if (conn != null){
               try {
                   System.out.println("事务滚回");
                   conn.rollback();
               } catch (SQLException ex) {
                   throw new RuntimeException(ex);
               }
           }
        }
    }
}
